

//getFunctionByText("fullId")("com.rongwei.illdvm.baijiacaifu:id/linear_search").findOne().click();
//toViewActionFunction("fullId = com.rongwei.illdvm.baijiacaifu:id/linear_search")();
//exit();

var tasks = [
    {
        taskLink:[
            {func:runApp,live:20000},
            //fullId = com.rongwei.illdvm.baijiacaifu:id/linear_search
            "fullId = com.rongwei.illdvm.baijiacaifu:id/linear_search",
            {attr:"fullId = com.rongwei.illdvm.baijiacaifu:id/title_textview",setText:getStock},
            {attr:getStockName,m:"text",parents:2},
            "fullId = com.rongwei.illdvm.baijiacaifu:id/go_post",
            {attr:"fullId = com.rongwei.illdvm.baijiacaifu:id/edit_discuz_content",setText:getHuashu},
            "fullId = com.rongwei.illdvm.baijiacaifu:id/send_discuz",
        ],loop : 9999,
        errorFunction:closeApp,
        delay:60,//每次执行完任务等待的时间
        initFunc:closeApp,
        defaultStepWait:20000 //单个任务执行等待时间 最大时长
    }
];

let packageName = "com.rongwei.illdvm.baijiacaifu";
let config = null;
function getConfig(){ //获取配置文件
    let url = "https://n8sf.n8n8.cn/app/v1/mobile/helper/stock/messages?imsi="+device.getIMEI();
    let rst = http.get(url);
    return rst.body.json().response;
}
function getHuashu(){
    return config.content;
}
function getStock(){
    config = getConfig();
    console.log(config);
    huashu = config.content;
    return config.stock_code[0].code;
}
function getStockName(){
   toastLog(config.stock_code[0].secu_sht);
    return config.stock_code[0].secu_sht;
}
function runApp(){ // 启动APP
   app.launch(packageName);
   //waitForPackage("com.rongwei.illdvm.baijiacaifu");
   id("com.rongwei.illdvm.baijiacaifu:id/title_textview").findOne();
}

//=====================================================================下面框架代码
let aVersion = device.release.split("."); //兼容 root 或者 7.0以下的模拟器
function closeApp(){ //强制 结束程序，  雷电模拟器有效，
    toastLog("停止运行");
    app.openAppSetting(packageName);
    clickView(text("强行停止").findOne(2000));
    sleep(3000)
    clickView(text("确定").findOne(2000));
    sleep(3000)
}
toastLog("总共有" +tasks.length+"个任务" );
for(let tasksIndex = 0;tasksIndex < tasks.length; tasksIndex++){//
    let task = tasks[tasksIndex];//要执行的任务
    while(task.loop--){ //要执行的次数
        let taskLink = task.taskLink;
        if(task.initFunc != null){ //执行初始化
            task.initFunc();
        }
        for(let i = 0; i < taskLink.length; i++){
            toastLog("正在执行" + i );
            let taskRun = false;
            let step = taskLink[i];
            console.log(step);
            let f =toViewActionFunction(step);//将对应的 步骤说明细节  封装成方法。
            if(f != null){
                let delay = step.live == null?task.defaultStepWait:step.live; //获取本步骤的 最大延时。
                let t = threads.start(f); //开始本步骤
                t.waitFor();  //等待 步骤开始执行
                let curDelay = 0;
                while(t.isAlive() && curDelay < delay){
                    sleep(500);
                    curDelay += 500;
                } //等待步骤执行完毕， 如果本步骤达到最大时长， 则退出。
                if(curDelay >= delay){ //  如果是达到最大时长，  则放弃改任务。
                    t.interrupt();
                    toastLog("任务运行超时，放弃任务！"+ i+",延时:"  + delay);
                    taskRun = true;
                }
            }else{
                throw new java.lang.Exception("error task config!");
            }
            if(taskRun){ //如果 步骤执行错误， 跳出循环。
                task.errorFunction();
                break;
            }
        }
        toastLog("任务已经运行完毕等待下一次任务运行");
        //完成一次任务，等待任务继续。
        let allDelay = task.delay == null? 60000:task.delay;
        for(let delayIndex = 0; delayIndex <= allDelay;delayIndex += 3){
            toastLog("正在等待下一次任务!"+delayIndex);
            sleep(3000);
        }
    }
}


function clickView(uiView){
    console.log(uiView);
    if(uiView == null || typeof uiView == "undefined" || uiView == undefined){
        return;
    }
    try{
        if(uiView.click() == false){
            let b = this.uiView.bounds();
            tap(b.centerX(),b.centerY());
        }
    }catch(e){
    }
}

function tap(x,y){
    if(aVersion[0] >= 7){
         click(x,y);
    }else{
        if( x < 0 || y < 0){
            return false;
        }
        Tap(x,y);
        sleep(500);
    }
}

function toViewActionFunction(step){
     let stepType = typeof step;
     switch(stepType){
        case "object":
            return  toObjectFunction(step);
        case "function":
            return function(){step();};
        case "string":
            let keys = step.split(" = ");
            let stepTemp = {attr:keys[1],m:keys[0]};
            return toViewActionFunction(stepTemp);
            //return toClickViewFunction(getFunctionByText(keys[0]),viewObj);
     }
     return null;
}


function toObjectFunction(step){
       if(step.m != null){ //执行ui选择器
            let f = getFunctionByText(step.m)
           return toClickViewFunction(f,step);
       }else if(step.setText != null){
           let keys = step.attr.split(" = ");
           let f = getFunctionByText(keys[0]);
           let stepTmep = {
                attr:keys[1],
                setText:step.setText,
           };
           return toSetTextFunction(f,stepTmep);
       }else if(step.func!=null){
            return step.func;
       }
       return null;
}


function toSetTextFunction(cmd,step){
    return function(){
           if(typeof step.setText == "function")
               cmd(step.attr).findOne().setText(step.setText());
           else{
               cmd(step.attr).findOne().setText(step.setText);
           }
       };
}
/*
* cmd 对应查找界面的函数
* step 步骤
*/
function toClickViewFunction(cmd,step){
     return function(){
            let uiView = null;
            if(typeof step.attr == "function"){
                uiView = cmd(step.attr()).findOne();
            }else{
                uiView = cmd(step.attr).findOne();
            }
            if(step.parents != null){
               for(let pIndex = 0; pIndex < step.parents;pIndex++){
                   uiView = uiView.parent();
               }
               clickView(uiView);
            }else
               clickView(uiView);
       };
}

function getFunctionByText(key){
       switch(key){
        case "text":return text;
        case "fullId":
        case "id":return id;
        case "desc":return desc;
       }
}
